package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.StringUtils;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.ViewUtil;
import com.zjlanyun.erp.view.BaseRFIDActivity;
import com.zjlanyun.erp.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class Rewind extends BaseRFIDActivity {

    @Bind(R.id.et_FBatchNO) EditText et_FBatchNO;
    @Bind(R.id.tv_FEmpName) TextView tv_FEmpName;
    @Bind(R.id.btn_select_emp) Button btn_select_emp;
    @Bind(R.id.et_FMOWidth) EditText et_FMOWidth;
    @Bind(R.id.et_FObjWidth) EditText et_FObjWidth;
    @Bind(R.id.et_FPoint1) EditText et_FPoint1;
    @Bind(R.id.et_FPoint2) EditText et_FPoint2;
    @Bind(R.id.et_FFuzheli) EditText et_FFuzheli;
    @Bind(R.id.et_FHoudu) EditText et_FHoudu;
    @Bind(R.id.et_FPointCheck) EditText et_FPointCheck;
    @Bind(R.id.et_FNGQty) EditText et_FNGQty;
    @Bind(R.id.et_FLLQty) EditText et_FLLQty;
    @Bind(R.id.et_FCLPQty) EditText et_FCLPQty;
    @Bind(R.id.et_FTXQty) EditText et_FTXQty;
    @Bind(R.id.et_FResult) EditText et_FResult;
    @Bind(R.id.et_FQty) EditText et_FQty;
    @Bind(R.id.et_Ftime) EditText et_Ftime;
    @Bind(R.id.et_FNote) EditText et_FNote;
    @Bind(R.id.sv) MyScrollView sv;

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.list) LinearLayout list;
    @Bind(R.id.ll_FBatchNO_Merge) LinearLayout ll_FBatchNO_Merge;
    @Bind(R.id.ll_body) LinearLayout ll_body;

    private boolean scaning = false;
    private String apiUrl = "";
    private ArrayList<String> mEpcList;
    private ArrayList<HashMap<String, Object>> mDataList;
    private String epc;
    private LayoutInflater mInflater;
    private boolean querying = false;
    private int curTag = -1;
    private ArrayList<HashMap<String, Object>> mEmpList;
    public static final int REQUESTCODE_SELECTEMP = 1;
    private boolean isMerge = true; //true复卷合并，false复卷拆分
    private boolean hasMaster = false; //true有母卷，false没有母卷，用于拆分的时候区分是否已经扫了母卷
    private boolean isSingleRewind = false; //是否单卷复卷
    private View curEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rewind);
        initBaseView();
        initView();
    }

    private void initView() {
        apiUrl = WebApi.production();
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));
        if (bundle.getString("title").equals("复卷合并") || bundle.getString("title").equals("复卷")) {
            isMerge = true;
        } else {
            ll_FBatchNO_Merge.setVisibility(View.GONE);
            isMerge = false;
        }
        if (bundle.getString("title").equals("复卷")) {
            isSingleRewind = true;
        }
        et_FNote.setOnTouchListener(onTouchListener);
        mEpcList = new ArrayList<>();
        mDataList = new ArrayList<>();
        ll_submit.setVisibility(View.VISIBLE);
        mInflater = LayoutInflater.from(mContext);
        tv_FEmpName.setText(AppConfig.getInstance().getString("username", ""));
        getEmp();

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEpcList.size() > 0) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });

        sv.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                ViewUtil.hideInputMethod(mContext, ll_submit);
                title.setFocusable(true);
                title.setFocusableInTouchMode(true);
                title.requestFocus();
                title.requestFocusFromTouch();

            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            String strEPC = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            if (isSingleRewind && mEpcList.size() > 0) {
                //单卷复卷，提示只能扫一卷
                Toastor.getInstance().showShortToast("请不要重复扫卡");
            } else if (!mEpcList.contains(strEPC) && !querying) {
                querying = true;
                epc = strEPC;
                getProductInfo();
            }
            //判断是否已经扫描了白卡
            if (mEpcList.contains(strEPC)) {
                boolean master = false;
                if (mDataList.size() > 0 && isMerge) {
                    //复卷合并、单卷复卷下判断母卷提示母卷已经扫描
                    for (HashMap<String, Object> item : mDataList) {
                        if (item.get("isMaster").toString().equals("1") && item.get("FMOBillNO").toString().equals(strEPC)) {
                            master = true;
                        }
                    }

                } else if (mDataList.size() > 0 && !isMerge) {
                    //复卷拆分下判断母卷提示母卷已经扫描
                    for (HashMap<String, Object> item : mDataList) {
                        if (item.get("isMaster").toString().equals("1") && item.get("FObjBillNO").toString().equals(strEPC)) {
                            master = true;
                        }
                    }
                }
                if (master) {
                    if (isSingleRewind) {
                        Toastor.getInstance().showShortToast("请不要重复扫卡");
                    } else {
                        Toastor.getInstance().showShortToast("该卡为母卷卡，已扫描");
                    }
                } else {
                    Toastor.getInstance().showShortToast("该卡为子卷卡，已扫描");
                }
            }
        }
    }

    /**
     * 获取产品信息
     */
    private void getProductInfo() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        if ((!isMerge && !hasMaster) || isMerge) {
            param.put("FGongXuNO", "107");
            param.put("FActionFlag", "fujuan");
        }
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getProductInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                if (!isMerge && hasMaster && data.optInt("FItemID") > 0) {
                    Toastor.getInstance().showShortToast("母卷已存在，请扫子卷卡");
                    querying = false;
                    return;
                } else if (!isMerge && !hasMaster && data.optInt("FItemID") == 0) {
                    Toastor.getInstance().showShortToast("请先扫描母卷卡");
                    querying = false;
                    return;
                } else if (isMerge && data.optInt("FItemID") == 0) {
                    Toastor.getInstance().showShortToast("该卡未绑定产品");
                    querying = false;
                    return;
                } else if (isMerge && !data.optString("FCurrentGongXuNO").equals("107")) {
                    //当前工序是107的才能做复卷
                    Toastor.getInstance().showShortToast("卡号：" + epc + "\n工序错误，无法复卷，请重新过拱门");
                    querying = false;
                    return;
                } else if (!isMerge && !hasMaster && !data.optString("FCurrentGongXuNO").equals("107")) {
                    //当前工序是107的才能做复卷
                    Toastor.getInstance().showShortToast("卡号：" + epc + "\n工序错误，无法复卷，请重新过拱门");
                    querying = false;
                    return;
                }
                if ((!isMerge && !hasMaster) || isMerge) {
                    if (!data.optString("FType").equals("30")) {
                        Toastor.getInstance().showShortToast("卡号：" + epc + "\n请先改成准备复卷");
                        querying = false;
                        return;
                    }
                }
                HashMap<String, Object> map = new HashMap<String, Object>();
                mEpcList.add(epc);
                View itemView = mInflater.inflate(R.layout.rewind_item, null);
                TextView tvepc = (TextView) itemView.findViewById(R.id.tv_epc);
                tvepc.setText(data.optString("epc"));
                TextView tvFGongxuName = (TextView) itemView.findViewById(R.id.tv_FGongxuName);
                tvFGongxuName.setText(data.optString("FGongxuName"));
                TextView fname = (TextView) itemView.findViewById(R.id.tv_FName);
                fname.setText(data.optString("FName"));
                TextView fnumber = (TextView) itemView.findViewById(R.id.tv_FNumber);
                fnumber.setText(data.optString("FNumber"));
                TextView pro_type = (TextView) itemView.findViewById(R.id.tv_pro_type);
                if (mEpcList.size() == 1) {
                    map.put("isMaster", "1");
                    pro_type.setText("（母卷）");
                } else {
                    map.put("isMaster", "0");
                    pro_type.setText("（子卷）");
                }
                TextView fbatchno = (TextView) itemView.findViewById(R.id.tv_FBatchNO);
                fbatchno.setText(data.optString("FBatchNO"));
                TextView fqty = (TextView) itemView.findViewById(R.id.tv_FQty);
                fqty.setText(String.valueOf(data.optDouble("FQty")));
                EditText FRecQty = (EditText) itemView.findViewById(R.id.et_FRecQty);
                FRecQty.addTextChangedListener(textWatcher);
                FRecQty.setOnTouchListener(onTouchListener);
                LinearLayout ll_xinmishu = (LinearLayout) itemView.findViewById(R.id.ll_xinmishu);
                LinearLayout ll_zhouhao = (LinearLayout) itemView.findViewById(R.id.ll_zhouhao);
                LinearLayout ll_FName = (LinearLayout) itemView.findViewById(R.id.ll_FName);
                LinearLayout ll_FBatchNO = (LinearLayout) itemView.findViewById(R.id.ll_FBatchNO);


                map.put("FRecQty", 0f); //收到米数
                map.put("FNote", data.optString("FNote"));
                if (isMerge) {
                    //复卷合并
                    map.put("FMOInterID", data.optString("FInterID"));
                    map.put("FMOBillNO", data.optString("epc"));
                    map.put("FMOBatchNO", data.optString("FBatchNO"));
                    map.put("FMOQty", data.optDouble("FQty"));
                    map.put("FMODate", data.optString("FDate"));
                    map.put("FMOWidth", data.optString("FWidth"));
                    map.put("FCLQty", data.optDouble("FCLQty"));
                    FRecQty.setTag(mEpcList.size() - 1);
                } else {
                    //复卷拆分
                    map.put("FObjInterID", data.optString("FInterID"));
                    map.put("FObjBillNO", data.optString("epc"));
                    map.put("FObjDate", data.optString("FDate"));
                    map.put("FObjQty", 0);
                    map.put("FBatchNO", ""); //轴号
                    map.put("FMOQty", data.optDouble("FQty"));
                    map.put("FMOWidth", data.optString("FWidth"));
                    map.put("FCLQty", data.optDouble("FCLQty"));

                    //拆分新数量的输入框
                    ll_xinmishu.setVisibility(View.VISIBLE);
                    ll_zhouhao.setVisibility(View.VISIBLE);
                    if (hasMaster) {
                        //有母卷了，再隐藏子卷
                        ll_FName.setVisibility(View.GONE); //子卡没有产品名称，隐藏
                        ll_FBatchNO.setVisibility(View.GONE); //子卡没有生产轴号，隐藏
                    }
                    EditText FObjQty = (EditText) itemView.findViewById(R.id.et_FObjQty);
                    FObjQty.addTextChangedListener(textWatcher);
                    FObjQty.setOnTouchListener(onTouchListener);
                    EditText et_FBatchNO_new = (EditText) itemView.findViewById(R.id.et_FBatchNO_new);
                    et_FBatchNO_new.addTextChangedListener(textWatcher);
                    et_FBatchNO_new.setOnTouchListener(onTouchListener);

                    et_FBatchNO_new.setTag(mEpcList.size() * 3 - 1);
                    FObjQty.setTag(mEpcList.size() * 3 - 2);
                    FRecQty.setTag(mEpcList.size() * 3 - 3);

                    //判断是否为母卷
                    if (data.optInt("FItemID") > 0) {
                        map.put("master", true);
                        hasMaster = true;
                    } else {
                        map.put("master", false);
                        FRecQty.setText("0");
                        FRecQty.setFocusableInTouchMode(false);
                        FRecQty.setEnabled(false);
                    }
                }
                list.addView(itemView);
                mDataList.add(map);
                querying = false;
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                querying = false;
            }
        });
    }

    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            curEditText = v;
            //记录数量
            if (v.getTag() != null) {
                curTag = (int) v.getTag();
            } else {
                curTag = -1;
            }

            //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
//            if ((v.getId() == R.id.et_FNote && Common.canVerticalScroll(et_FNote))) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//                if (event.getAction() == MotionEvent.ACTION_UP) {
//                    v.getParent().requestDisallowInterceptTouchEvent(false);
//                }
//            }

            return false;
        }
    };

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (curTag > -1) {
                if (isMerge) {
                    if (!s.toString().equals(""))
                        mDataList.get(curTag).put("FRecQty", Double.valueOf(s.toString()));
                } else {
                    if ((curTag % 3) == 0) {
                        mDataList.get(curTag / 3).put("FRecQty", StringUtils.toDouble(s.toString(), 0));
                    } else if ((curTag % 3) == 1) {
                        mDataList.get(curTag / 3).put("FObjQty", StringUtils.toDouble(s.toString(), 0));
                    } else {
                        mDataList.get(curTag / 3).put("FBatchNO", s.toString());
                    }
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    /**
     * 提交
     */
    @OnClick(R.id.ll_submit)
    public void postRewind() {
        if (et_FBatchNO.getText().toString().equals("") && isMerge) {
            Toastor.getInstance().showShortToast("请输入复卷轴号");
            return;
        } else if (mDataList.size() == 0) {
            Toastor.getInstance().showShortToast("请扫卡");
            return;
        } else if (et_FQty.getText().toString().equals("") && isMerge) {
            Toastor.getInstance().showShortToast("请输入发货米数");
            return;
        } else if (!isMerge && mDataList.size() < 2) {
            Toastor.getInstance().showShortToast("复卷拆分数据最少需扫描2张卡");
            return;
        }

        if (!isMerge) {
            //新米数、新轴号必填检查
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).get("FObjQty").toString().equals("0")) {
                    Toastor.getInstance().showShortToast("新米数必须填写");
                    return;
                }
                if (mDataList.get(i).get("FBatchNO").toString().equals("")) {
                    Toastor.getInstance().showShortToast("新轴号必须填写");
                    return;
                }
            }
        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("list", JSON.toJSONString(mDataList));
        param.put("FBatchNO", et_FBatchNO.getText().toString().replace(" ", "").toUpperCase());
        param.put("FEmpName", tv_FEmpName.getText().toString());
        param.put("FMOWidth", et_FMOWidth.getText().toString());
        param.put("FObjWidth", et_FObjWidth.getText().toString());
        param.put("FPoint1", et_FPoint1.getText().toString());
        param.put("FPoint2", et_FPoint2.getText().toString());
        param.put("FFuzheli", et_FFuzheli.getText().toString());
        param.put("FHoudu", et_FHoudu.getText().toString());
        param.put("FPointCheck", et_FPointCheck.getText().toString());
        param.put("FNGQty", et_FNGQty.getText().toString());
        param.put("FLLQty", et_FLLQty.getText().toString());
        param.put("FCLPQty", et_FCLPQty.getText().toString());
        param.put("FTXQty", et_FTXQty.getText().toString());
        param.put("FResult", et_FResult.getText().toString());
        param.put("FQty", et_FQty.getText().toString().equals("") ? 0 : et_FQty.getText().toString());
        param.put("Ftime", et_Ftime.getText().toString());
        param.put("FNote", et_FNote.getText().toString());
        param.put("merge", isMerge);
        param.put("FGongXuNO", "107");
        param.put("FActionFlag", "fujuan");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postRewind", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                clean();
                Toastor.getInstance().showShortToast(R.string.submit_success);
            }
        });
    }

    /**
     * 选择责任人
     */
    @OnClick(R.id.btn_select_emp)
    public void select_emp() {
        if (mEmpList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择责任人");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mEmpList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_SELECTEMP);
        } else {
            Toastor.getInstance().showShortToast("无责任人数据");
        }
    }

    /**
     * 获取职员
     */
    private void getEmp() {
        mEmpList = new ArrayList<>();
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getEmp", true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                JSONArray emp = data.optJSONArray("empList");
                for (int i = 0; i < emp.length(); i++) {
                    JSONObject item = emp.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    map.put("FNumber", item.optString("FNumber"));
                    mEmpList.add(map);
                }
            }
        });
    }

    private void clean() {
        et_FBatchNO.setText("");
        et_FMOWidth.setText("");
        et_FObjWidth.setText("");
        et_FPoint1.setText("");
        et_FPoint2.setText("");
        et_FFuzheli.setText("");
        et_FHoudu.setText("");
        et_FPointCheck.setText("");
        et_FNGQty.setText("");
        et_FLLQty.setText("");
        et_FCLPQty.setText("");
        et_FTXQty.setText("");
        et_FResult.setText("");
        et_Ftime.setText("");
        et_FNote.setText("");
        et_FQty.setText("");
        list.removeAllViews();
        curTag = -1;
        mDataList.clear();
        mEpcList.clear();
        hasMaster = false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mEpcList.size() > 0) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_SELECTEMP && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            tv_FEmpName.setText(mEmpList.get(p).get("FName").toString());
        }
    }
}
